<template>
  <!-- 添加或修改付款申请单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>供应商信息</span>
              </div>
              <el-descriptions class="margin-top " :contentStyle="CS" :label-style="LS" title="" :column="1"
                               size="medium" border>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    供应商名称
                  </template>
                  {{ buy.supplierName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-money"></i>
                    供应商银行
                  </template>
                  {{ buy.bankName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-c-scale-to-original"></i>
                    供应商行号
                  </template>
                  {{ buy.bankNo }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-bank-card"></i>
                    供应商账号
                  </template>
                  {{ buy.accountNo }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">

              <el-col :span="24">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker clearable v-model="form.applyTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                                  placeholder="请选择申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票编号" prop="invoiceCode">
                  <el-input type="textarea" v-model="form.invoiceCode" placeholder="请输入发票编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票照片" prop="invoicePhoto">
                  <file-upload-invoice v-model="form.invoicePhoto"
                                       @getInvoiceInfo="getInvoiceInfo"></file-upload-invoice>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请金额:" prop="totalMoney">
                  <el-input-number  :max="maxTotalMoney" v-model="form.totalMoney" disabled
                                   :precision="2"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">提 交 付 款 申 请</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {accAdd, accDiv, accMul, addAction, getAction, getById, isEmpty, updateAction} from '@/api/manage';
import moment from 'moment';
import {parseTime} from "@/utils/common";
import CaigouDetaiList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";
import Decimal from "decimal.js";

export default {
  name: "PayApplyIronForm",
  dicts: ["yes_no"],
  components: {CaigouDetaiList},
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        payApplyBuyDetailList: [],
      },
      payApplyBuyDetailList: [],
      // 总条数
      total: 0,
      goodsMoney: 0,
      maxTotalMoney: 0,
      // 查询参数
      queryParams: {
        cgallid: null,
        pageNum: 1,
        pageSize: 20,
        mainId: null,
        name: null,
        brand: null,
        unit: null,
        costPrice: null,
        count: null,
        cost: null,
        validityTerm: null,
        buyId: null,
        buyName: null,
        buyDate: null,
        buyType: null,
        reimburse: null,
        supplierId: null,
        supplierName: null,
        dateRange: "",
        params: {},
      },
      buy: {},
      buyId: null,
      // 表单校验
      rules: {
        applyTime: [
          {required: true, message: "请选择申请时间", trigger: "blur"}
        ],
        totalMoney: [
          {required: true, message: "请输入申请付款金额", trigger: "blur"},
          {
            validator: this.totalMoneyValidator,
            trigger: 'blur'
          }
        ],
      },
      url: {
        getById: '/payApply/payApply/',
        addForDeposit: '/payApply/payApply/addForDeposit',
        addForIron: '/payApply/payApply/addForIron',
        edit: '/payApply/payApply/edit',
        generateMoneyList: '/payApply/payApply/generateMoneyList',
      },
      CS: {
        'text-align': 'center',  //文本居中
        'min-width': '250px',   //最小宽度
        'word-break': 'break-all'  //过长时自动换行
      },
      LS: {
        'color': '#000',
        'text-align': 'center',
        'font-weight': '600',
        'height': '40px',
        'min-width': '110px',
        'word-break': 'keep-all'
      }
    };
  },
  created() {

  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        buyId: null,
        applyTime: null,
        invoiceCode: "",
        invoicePhoto: null,
        totalMoney: null,
        paidMoney: null,
        remainMoney: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    totalMoneyValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('申请金额不能为0'));
      } else {
        callback();
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加付款申请单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改付款申请单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = Object.assign({});
          // 把form里面值放进 params
          params = that.form;
          params.payApplyBuyDetailList = that.payApplyBuyDetailList;
          if (this.form.id != null) {
            updateAction(this.url.edit, params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.addForIron, this.form).then(response => {
              this.$modal.msgSuccess("付款单申请成功");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });
    },

    show(row) {
      this.reset();
      this.buy = row;
      this.buyId = row.id;
      this.open = true;
      this.form.applyTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.title = "付款申请单";
      this.queryParams.mainId = row.id;
      this.form.buyId = row.id;
      this.goodsMoney = row.money;
      this.form.totalMoney = row.money - row.payApplyTotalMoney;
      this.maxTotalMoney = row.money - row.payApplyTotalMoney;
      this.form.supplierId = row.supplierId;
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        let values;
        if (column.property === "buyDetail.goodsBuyTotal") {
          values = data.map((item) => Number(item.buyDetail.goodsBuyTotal));
        } else if (column.property === "buyDetail.shengyu") {
          values = data.map((item) => Number(item.buyDetail.shengyu));
        } else if (column.property === "buyDetail.dun") {
          values = data.map((item) => Number(item.buyDetail.dun));
        } else {
          values = data.map((item) => Number(item[column.property]));
        }
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "buyDetail.dun" || column.property === "shengyu" || column.property === "buyDetail.goodsBuyTotal" || column.property === "buyDetail.shengyu") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              let number = new Decimal(accAdd(prev, curr));
              return number.toFixed(2);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    getInvoiceInfo(info) {
      // form.invoiceCode 不能为空 多个发票用，隔开
      if (!isEmpty(this.form.invoiceCode)) {
        this.form.invoiceCode += ",";
      } else {
        this.form.invoiceCode = "";
      }
      this.form.invoiceCode += info.number;
    }


  }
};
</script>
